var express = require('express');
var router = express.Router();
//引入handlerFile.js
const { uploadFiles, moveFiles, deleteFiles } = require('./../util/handleFiles');

const path = require('path');
router.post('/image', function (req, res, next) {
    //会针对传入的图片生成一个专门上传的图片函数
    // let path = 'assets';//自定义保存图片的文件夹，会直接放在/public下
    let path = 'temp';//自定义保存图片的文件夹，会直接放在/public下
    const uploadImages = uploadFiles({
        path: `./public/${path}`,
        //formdata.append()的第一个参数
        key: 'file',
        //图片的大小限制,1mb以内
        size: 1024
    });
    //上传函数
    uploadImages(req, res, (err) => {
        //图片上传失败或成功都会调用的回调函数
        if (err) {
            //上传失败
            console.log(err);
            res.send({ message: "上传失败", code: -1 })
        } else {
            //上传成功
            //将上传成功之后图片的路径发送给前端
            res.send({
                message: '上传成功',
                data: `${req.files[0].filename}`,
                code: 200
            })
        }   
    })
})

router.post('/del', function (req, res, next) {

    let str= req.body.imgSrc;
    let delPath = `../public/${str}`;
    let data=path.resolve(__dirname,delPath)
    console.log(data);
    // console.log(path.resolve(__dirname,delPath));
   const code= deleteFiles(data);
   console.log(code);
    res.send({code});
    // deleteImages

})
//确认添加
router.post('/addImage', function (req, res, next) {

    // let str= req.body.imgSrc;
    let addPath1 = `../public/temp`;
    let addPath2 = `../public/assets`;
    let data1=path.resolve(__dirname,addPath1);
    let data2=path.resolve(__dirname,addPath2);
    console.log(data1);
    console.log(data2);
    // console.log(path.resolve(__dirname,delPath));
  let code=  moveFiles({
    fromPath:data1, 
    toPath:data2,
    filename: req.body.imgSrc
    })
    res.send({code});
    // deleteImages

})

module.exports = router;
